<?php  

/**
 * forgotten.php
 *
 * Forgotten password
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestForgottenphone extends RestController {
	
	/*
	* forgotten password
	*/
	public function forgottenphone() {
    //验证用户是否已经登陆
		$this->checkPlugin();
		
		$json = array('success' => true);
    //验证是否是post请求
		if ( $_SERVER['REQUEST_METHOD'] === 'POST'){
			
			$requestjson = file_get_contents('php://input');
            $post = json_decode($requestjson, true);

			if (0&&$this->customer->isLogged()) {
				$json['error']['warning']		= "用户已经登陆了";
				$json['success']	= false;			
			} else {
                $this->load->model('account/customer');
                
                $error = $this->validate($post);
                if(empty($error)){
                    
                //存入数据库
                    $this->model_account_customer->editPasswordwithphone($post['telephone'], $post['password']);

                    //登录
                    if(!$this->customer->isLogged()) {
                        $this->customer->login($post['telephone'], $post['password']);    
                    }
                   
                    // 记录活动日志
                    $customer_info = $this->model_account_customer->getCustomerByTelephone($post['telephone']);

                    if ($customer_info) {
                        $this->load->model('account/activity');

                        $activity_data = array(
                            'customer_id' => $customer_info['customer_id'],
                            'name'        => $customer_info['telephone'] );
                

                        $this->model_account_activity->addActivity('forgottenphone', $activity_data);
                    }
                } else {
                    $json["error"]		= $error;
                    $json["success"]	= false;
                }
            }
		} else {
				$json["error"]['warning']		= "不是post请求";
				$json["success"]	= false;
		}

		$this->sendResponse($json);
	
	}

    protected function validate($post) {
        $error = array();
        if ((utf8_strlen($post['password']) < 6) || (utf8_strlen($post['password']) > 32)) {
                $error['warning'] = "密码小于6位或者大于32位";
        } elseif(!isset($post['telephone'])) {
            $error['warning'] = "手机号码不得为空";
        } elseif (!$this->model_account_customer->getTotalCustomersByTelephone($post['telephone'])) {
            $error['warning'] = "没有这个用户";
        }
        $this->load->model('account/smsmobile');
        if($this->model_account_smsmobile->verifySmsCode($post['telephone'], $post['sms_code']) == 0) {
            $error['warning'] = "验证码错误";
        }
        return $error;
    }
}